今天在 Hackerrank 的主題是,延續我們之前研究的 Linked list,為這個 Linked list 去增加一個 Function 來把 Linked list 中重複值的節點給移除掉。為了簡單起見,這裡重複的值必須是連續的,例如 1 2 2 3 3
會變成 1 2 3
,但 1 3 1 3
還是一樣 1 3 1 3
。那就讓我們開始吧!(其實不是很懂 Hackerrank 為什麼要出這題,哈哈哈!)
class Node:
def __init__(self, data):
self.data = data
self.next = None
def display(head):
current = head
while current:
print(current.data, end=' ')
current = current.next
def insert(head, data):
node = Node(data)
if head is None:
head = node
else:
current = head
while(current.next is not None):
current = current.next
current.next = node
return head
def remove_duplicates(head):
curr = head
while curr is not None and curr.next is not None:
while curr.next is not None and curr.data is curr.next.data:
curr.next = curr.next.next
curr = curr.next
return head
time = int(input())
head = None
for i in range(time):
data = int(input())
head = insert(head, data)
remove_duplicates(head)
display(head)
remove_duplicates
,概念上就是當找到相鄰若是相同的,那就忽略掉重複的 Node
,讓目前的 Node
(curr
) 的 next
略過本來的下一個 Node 去指到下下個 Node
,假設還是重複就繼續下去直到不重複為止。相信看上述程式的部分應該不難懂囉!